import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api } from '../api/request'

// 使用统一的request实例

export const useUserStore = defineStore('user', () => {
  // 用户基本信息
  const userInfo = ref({
    id: 1,
    username: 'system',
    email: 'system@xiaozhi.com',
    realName: '系统用户',
    phone: '',
    role: 'ADMIN',
    avatar: '/OIP.webp'
  })
  const isLoggedIn = computed(() => true) // 始终返回已登录状态
  const token = computed(() => 'no-token-required') // 不再需要真实token
  
  // 健康档案
  const healthRecord = ref({
    allergies: '',
    medicalHistory: '',
    familyHistory: '',
    currentMedications: '',
    height: null,
    weight: null,
    bloodType: ''
  })
  
  // 预约信息
  const appointments = ref([])
  
  // 通知消息
  const notifications = ref([])
  
  // 用户登录（简化版，无需实际认证）
  const login = async (credentials) => {
    try {
      // 直接设置默认用户信息，无需后端验证
      userInfo.value = {
        id: 1,
        username: credentials.username || 'system',
        email: 'system@xiaozhi.com',
        realName: credentials.username || '系统用户',
        phone: '',
        role: 'ADMIN',
        avatar: '/OIP.webp'
      }
      
      // 设置模拟token
      const mockToken = 'mock-jwt-token-' + Date.now()
      localStorage.setItem('token', mockToken)
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
      
      // 加载用户健康档案和预约信息
      await loadHealthRecord()
      await loadAppointments()
      
      return { success: true }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: true } // 即使出错也返回成功，确保用户可以继续使用
    }
  }
  
  // 用户注册（简化版，无需实际注册）
  const register = async (userData) => {
    try {
      // 直接设置用户信息，无需后端注册
      userInfo.value = {
        id: 1,
        username: userData.username,
        email: userData.email || 'system@xiaozhi.com',
        realName: userData.realName || userData.username,
        phone: userData.phone || '',
        role: 'ADMIN',
        avatar: '/OIP.webp'
      }
      
      return { success: true }
    } catch (error) {
      console.error('注册失败:', error)
      return { success: true } // 即使出错也返回成功
    }
  }
  
  // 用户登出（简化版，保持用户状态）
  const logout = () => {
    // 不再清除用户信息，保持登录状态
    console.log('用户登出（但保持系统访问权限）')
  }
  
  // 更新用户信息
  const updateUserInfo = async (newInfo) => {
    try {
      const response = await api.put('/api/user/profile', newInfo)
      
      if (response.success) {
        userInfo.value = { ...userInfo.value, ...response.data }
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('更新用户信息失败:', error)
      const message = error.response?.message || '更新用户信息失败，请稍后重试'
      return { success: false, message }
    }
  }
  
  // 加载健康档案
  const loadHealthRecord = async () => {
    try {
      const response = await api.get('/api/health/record')
      
      if (response.success && response.data) {
        healthRecord.value = {
          allergies: response.data.allergies || '',
          medicalHistory: response.data.medicalHistory || '',
          familyHistory: response.data.familyHistory || '',
          currentMedications: response.data.currentMedications || '',
          height: response.data.height || null,
          weight: response.data.weight || null,
          bloodType: response.data.bloodType || ''
        }
      }
    } catch (error) {
      console.error('加载健康档案失败:', error)
    }
  }
  
  // 更新健康档案
  const updateHealthRecord = async (newRecord) => {
    try {
      const response = await api.put('/api/health/record', newRecord)
      
      if (response.success) {
        healthRecord.value = { ...healthRecord.value, ...newRecord }
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('更新健康档案失败:', error)
      const message = error.response?.message || '更新健康档案失败，请稍后重试'
      return { success: false, message }
    }
  }
  
  // 加载用户预约
  const loadAppointments = async () => {
    try {
      console.log('开始加载预约信息...')
      const response = await api.get('/api/appointments/my')
      
      console.log('预约信息响应:', response)
      
      if (response && response.success) {
        appointments.value = response.data || []
        console.log('预约信息加载成功:', appointments.value)
      } else {
        console.warn('预约信息响应格式异常:', response)
        appointments.value = []
      }
    } catch (error) {
      console.error('加载预约信息失败:', error)
      // 输出更详细的错误信息用于调试
      if (error.response) {
        console.error('错误响应:', error.response.status, error.response.data)
      } else if (error.request) {
        console.error('网络请求错误:', error.request)
      } else {
        console.error('其他错误:', error.message)
      }
      appointments.value = []
    }
  }
  
  // 创建预约
  const createAppointment = async (appointmentData) => {
    try {
      const response = await api.post('/api/appointments', appointmentData)
      
      if (response.success) {
        // 重新加载预约列表
        await loadAppointments()
        return { success: true, data: response.data }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('创建预约失败:', error)
      const message = error.response?.message || '创建预约失败，请稍后重试'
      return { success: false, message }
    }
  }
  
  // 取消预约
  const cancelAppointment = async (appointmentId) => {
    try {
      const response = await api.put(`/api/appointments/${appointmentId}/cancel`)
      
      if (response.success) {
        // 重新加载预约列表
        await loadAppointments()
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('取消预约失败:', error)
      const message = error.response?.message || '取消预约失败，请稍后重试'
      return { success: false, message }
    }
  }
  
  // 初始化用户数据（从localStorage恢复）
  const initializeUser = async () => {
    const savedUserInfo = localStorage.getItem('userInfo')
    const token = localStorage.getItem('token')
    
    if (savedUserInfo && token) {
      try {
        userInfo.value = JSON.parse(savedUserInfo)
        // 验证token是否有效，并加载最新数据
        await loadHealthRecord()
        await loadAppointments()
      } catch (error) {
        console.error('恢复用户数据失败:', error)
        // 清除无效数据
        logout()
      }
    }
  }
  
  return {
    // 状态
    userInfo,
    isLoggedIn,
    token,
    healthRecord,
    appointments,
    notifications,
    
    // 方法
    login,
    register,
    logout,
    updateUserInfo,
    loadHealthRecord,
    updateHealthRecord,
    loadAppointments,
    createAppointment,
    cancelAppointment,
    initializeUser
  }
})